<template>
  <el-container style="height: 100vh;">
    <!-- 左侧导航栏 -->
    <el-aside width="220px" style="background: #222d32; color: #fff; min-height: 100vh;">
      <div style="height: 60px; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: bold; letter-spacing: 2px; color: #fff; border-bottom: 1px solid #1e282c;">
        在线商城系统
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical-demo"
        background-color="#222d32"
        text-color="#fff"
        active-text-color="#409EFF"
        router
        style="border-right: none; margin-top: 0;"
      >
        <el-menu-item index="/">
          <i class="el-icon-house"></i>
          <span>首页</span>
        </el-menu-item>
        <el-menu-item index="/profile">
          <i class="el-icon-user"></i>
          <span>个人信息</span>
        </el-menu-item>
        <el-menu-item index="/profile/orders">
          <i class="el-icon-document"></i>
          <span>我的订单</span>
        </el-menu-item>
        <el-menu-item index="/profile/address">
          <i class="el-icon-location"></i>
          <span>收货地址</span>
        </el-menu-item>
        <el-menu-item index="/profile/balance">
          <i class="el-icon-wallet"></i>
          <span>个人余额</span>
        </el-menu-item>
        <el-menu-item index="/logout" @click="logout">
          <i class="el-icon-switch-button"></i>
          <span>退出登录</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main style="background: #f5f6fa;">
      <div v-if="$route.path === '/profile'" style="max-width: 500px; margin: 40px auto;">
        <el-card shadow="hover">
          <template #header>
            <span style="font-size: 20px; font-weight: bold;">个人信息</span>
          </template>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" style="margin-top: 20px;">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" :disabled="!editMode" maxlength="20" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" :disabled="!editMode" maxlength="20" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" :disabled="!editMode" maxlength="50" />
            </el-form-item>
            <el-form-item>
              <el-button v-if="!editMode" type="primary" @click="editMode = true">编辑</el-button>
              <el-button v-else type="primary" @click="onSave">保存</el-button>
              <el-button v-if="editMode" @click="onCancel">取消</el-button>
              <el-button type="warning" @click="showPwdDialog = true">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 修改密码弹窗 -->
        <el-dialog v-model="showPwdDialog" title="修改密码" width="400px">
          <el-form :model="pwdForm" :rules="pwdRules" ref="pwdFormRef" label-width="80px">
            <el-form-item label="原密码" prop="oldPwd">
              <el-input v-model="pwdForm.oldPwd" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd">
              <el-input v-model="pwdForm.newPwd" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPwd">
              <el-input v-model="pwdForm.confirmPwd" type="password" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showPwdDialog = false">取消</el-button>
            <el-button type="primary" @click="onChangePwd">保存</el-button>
          </template>
        </el-dialog>
      </div>
      <router-view v-else />
    </el-main>
  </el-container>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { ElMessageBox, ElMessage } from 'element-plus'
import { computed, ref, reactive, onMounted } from 'vue'
import { getUserProfile, updateUserProfile, changeUserPassword } from '@/utils/request'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const activeMenu = computed(() => {
  if (route.path === '/') return '/'
  if (route.path.startsWith('/profile/orders')) return '/profile/orders'
  if (route.path.startsWith('/profile/address')) return '/profile/address'
  if (route.path === '/profile') return '/profile'
  return ''
})

function logout() {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    type: 'warning',
    confirmButtonText: '退出',
    cancelButtonText: '取消',
  }).then(() => {
    userStore.logout()
    router.push('/login')
  })
}

// 个人信息表单
const formRef = ref()
const form = reactive({
  nickname: '',
  phone: '',
  email: ''
})
const editMode = ref(false)

const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度2-20位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

// 获取用户信息（对接后端API）
async function fetchProfile() {
  try {
    const res = await getUserProfile()
    if (res.success && res.data) {
      form.nickname = res.data.nickname || ''
      form.phone = res.data.phone || ''
      form.email = res.data.email || ''
      // 同步到userStore
      userStore.user = { ...userStore.user, ...res.data }
    } else {
      ElMessage.error(res.message || '获取用户信息失败')
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
}
onMounted(fetchProfile)

async function onSave() {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        const res = await updateUserProfile({
          nickname: form.nickname,
          phone: form.phone,
          email: form.email
        })
        if (res.success) {
          ElMessage.success('保存成功')
          editMode.value = false
          fetchProfile()
        } else {
          ElMessage.error(res.message || '保存失败')
        }
      } catch (e) {
        ElMessage.error('保存失败')
      }
    }
  })
}
function onCancel() {
  editMode.value = false
  fetchProfile()
}

// 修改密码弹窗
const showPwdDialog = ref(false)
const pwdFormRef = ref()
const pwdForm = reactive({
  oldPwd: '',
  newPwd: '',
  confirmPwd: ''
})
const pwdRules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' }
  ],
  confirmPwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value) => value === pwdForm.newPwd, message: '两次输入密码不一致', trigger: 'blur' }
  ]
}
async function onChangePwd() {
  pwdFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const res = await changeUserPassword({
          oldPassword: pwdForm.oldPwd,
          newPassword: pwdForm.newPwd
        })
        if (res.success) {
          ElMessage.success('密码修改成功')
          showPwdDialog.value = false
          pwdForm.oldPwd = ''
          pwdForm.newPwd = ''
          pwdForm.confirmPwd = ''
        } else {
          ElMessage.error(res.message || '密码修改失败')
        }
      } catch (e) {
        ElMessage.error('密码修改失败')
      }
    }
  })
}
</script>

<style scoped>
.el-menu-vertical-demo {
  border-right: none;
  margin-top: 0;
}
.el-menu-item {
  font-size: 16px;
  height: 48px;
  line-height: 48px;
}
.el-menu-item.is-active {
  background: #1e282c !important;
}
</style>
